﻿Imports System.Data
Imports Sybase.Data.AseClient

Imports System.IO
Imports System.Text

Imports System.Xml

Imports System.Windows.Media
Imports System.ComponentModel

Imports Microsoft.Office.Interop.Excel
Imports System.Collections.ObjectModel

Class CMExtraccionFicheros

    Private ConsultaServicio As New CConsultaServicio()
    Private lstResultado     As New System.Data.DataTable()
    Private idConsulta       As Integer

    Public Sub New()
        Try
            InitializeComponent()
            CargaTipoConsultas()
        Catch ex As Exception
            MessageBox.Show("Error TI500. Error al cargar tipo de consultas: " & ex.Message,"Extracción de Ficheros", MessageBoxButton.OK, MessageBoxImage.Error)
        Finally
            Mouse.OverrideCursor = Nothing
        End Try

    End Sub

    #Region "Cargas iniciales"

        Public Sub CargaTipoConsultas()
            Dim lstConsultas = ConsultaServicio.ObtieneConsultas()
            cmbTipoConsulta.ItemsSource = lstConsultas
            cmbTipoConsulta.SelectedIndex = 0
            btnConsultar.IsEnabled = True
        End Sub
    #End Region
    
    #Region "Eventos de Click"

        Private Sub btnConsultar_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnConsultar.Click
            Try
                Mouse.OverrideCursor = Cursors.Wait
                LimpiaGrid()
                Dim consulta As CConsulta
                consulta = cmbTipoConsulta.SelectedItem
                lstResultado = New System.Data.DataTable()
                Dim intBitacora As Integer = CUtileria.GrabarBitacora("ExtraccionFicheros", "RealizaBúsqueda", "Realiza la búsqueda de consulta con ID: " + consulta.Id.ToString)
                lstResultado = ConsultaServicio.ObtieneResultadoConsulta(consulta.Id, consulta.RutaArchivo)
                If lstResultado.Rows.Count > 0 Then
                    grdInformacion.ItemsSource = lstResultado.DefaultView
                    brdInformacion.Visibility = System.Windows.Visibility.Visible
                    btnExportar.IsEnabled = True
                    btnLimpiar.IsEnabled = True
                    idConsulta = consulta.Id
                Else
                    MessageBox.Show("No existe información con la consulta realizada.", "Extracción de Ficheros", MessageBoxButton.OK, MessageBoxImage.Information)
                End If
                CUtileria.CompletarRegBitacora(intBitacora)
            Catch ex As Exception
                Dim intErrorBitacora As Integer = CUtileria.GrabarBitacora("ExtraccionFicheros", "Error-RealizaBúsqueda", ex.Message)
                CUtileria.CompletarRegBitacora(intErrorBitacora)
                MessageBox.Show("Error TI500. Error al realizar la consulta: " & ex.Message, "Extracción de Ficheros", MessageBoxButton.OK, MessageBoxImage.Error)
            Finally
                Mouse.OverrideCursor = Nothing
            End Try
        End Sub

        Private Sub btnLimpiar_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnLimpiar.Click
            Try
                Mouse.OverrideCursor = Cursors.Wait
                LimpiaGrid()
            Catch ex As Exception
                 MessageBox.Show("Error TI500. Error al limpiar grid: " & ex.Message, "Extracción de Ficheros", MessageBoxButton.OK, MessageBoxImage.Error)
            Finally
                Mouse.OverrideCursor = Nothing
            End Try
        
        
        End Sub

        Private Sub btnExportar_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnExportar.Click
            Try
                Mouse.OverrideCursor = Cursors.Wait
                Dim intBitacora As Integer = CUtileria.GrabarBitacora("ExtraccionFicheros", "ExportarCsv", "Se exporta Info de consulta con ID: " + idConsulta.ToString)
                Dim resultadoDialogo As Boolean
                Dim dialog As New Microsoft.Win32.SaveFileDialog()
                Dim separador As String = ";"
                Dim nombreFichero As String
                nombreFichero = ConsultaServicio.ObtieneNombreFichero(idConsulta)
                dialog.FileName = nombreFichero
                dialog.DefaultExt = ".csv"
                dialog.Filter = "CSV documents (.csv)|*.csv"

                resultadoDialogo = dialog.ShowDialog()
            
                If resultadoDialogo Then
                    ConsultaServicio.ActualizaConsecutivo(idConsulta)
                    Dim sw As StreamWriter = New StreamWriter(dialog.FileName)
                    Dim sb As StringBuilder = New StringBuilder()
                
                    For Each columna As DataGridColumn In grdInformacion.Columns
                        sb.Append(columna.Header.ToString() + separador)
                    Next
                    sb.Replace(separador, vbNewLine, sb.Length - 1, 1)

                    Dim collection As ItemCollection = grdInformacion.Items

                    For Each data As DataRowView In collection
                        Dim registro As DataRow = data.Row

                        For columna As Integer = 1 To grdInformacion.Columns.Count
                            sb.Append(registro(columna - 1).ToString().Trim().Replace(",", "") + separador)
                        Next

                        sb.Replace(separador, vbNewLine, sb.Length - 1, 1)
                    Next
                    
                    sw.Write(sb.ToString().Trim())
                    sw.Close()
                End If
                CUtileria.CompletarRegBitacora(intBitacora)
            Catch ex As Exception
                Dim intErrorBitacora As Integer = CUtileria.GrabarBitacora("ExtraccionFicheros", "Error-ExportarCsv", ex.Message)
                CUtileria.CompletarRegBitacora(intErrorBitacora) 
                MessageBox.Show("Error TI500. Error al generar el fichero: " & ex.Message, "Extracción de Ficheros", MessageBoxButton.OK, MessageBoxImage.Error)
            Finally
                Mouse.OverrideCursor = Nothing
            End Try
        End Sub

    #End Region
    
    #Region  "Funciones comunes"
        Private Sub LimpiaGrid()
            idConsulta = Nothing
            grdInformacion.ItemsSource = Nothing
            brdInformacion.Visibility = System.Windows.Visibility.Hidden
            btnExportar.IsEnabled = False
            btnLimpiar.IsEnabled = False
        End Sub

    #End Region

    

    

End Class
